<?php
namespace App\Admin\Extensions;

use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Address;

class EthsExporter extends AbstractExporter
{
    protected $head = [];
    protected $body = [];
    public function setAttr($head, $body){
        $this->head = $head;
        $this->body = $body;
    }

    public function export()
    {
        Excel::create('Filename', function($excel) {
            $excel->sheet('Sheetname', function($sheet) {
                // 这段逻辑是从表格数据中取出需要导出的字段
                $head = $this->head;
                $body = $this->body;
                $bodyRows = collect($this->getData())->map(function ($item)use($body) {
                    foreach ($body as $keyName){
                        switch ($keyName) {
                            case 'status' :
                                $status = array_get($item, $keyName);
                                switch ($status) {
                                    case 0 :
                                        $status = "待审核";
                                        break;
                                    case 1 :
                                        $status = "已审核";
                                        break;
                                    case 2 :
                                        $status = "已驳回";
                                        break;
                                }
                                $arr[] = $status;
                                break;
                            case 'to_address_id' :
                                $to_address_id = array_get($item, $keyName);
                                if($data = Address::find($to_address_id)){
                                    $arr[] =  $data->address;
                                }else{
                                    $arr[] =  '暂无收款地址';
                                }
                                break;
                            //过滤掉  不处理参数
                            case 'type' : break;
                            case 'created_at' : break;
                            case 'deleted_at' : break;
                            default:
                                $arr[] = array_get($item, $keyName);
                                break;
                        }
                    }
                    return $arr;
                });
                $rows = collect([$head])->merge($bodyRows);
                $sheet->rows($rows);
            });
        })->export('xls');//.xls .csv ...
    }
}